package com.tudouji.project.pay.service.impl;

import com.flow.service.pojo.BasePojo;
import com.flow.service.pojo.ResultParam;
import com.flow.service.pojo.result.FlowResult;
import com.flow.service.process.service.IFlowBaseService;
import com.flow.service.process.service.impl.FlowProcessProxy;
import com.github.pagehelper.PageHelper;
import com.tudouji.common.utils.DateUtils;
import com.tudouji.common.utils.IdUtils;
import com.tudouji.common.utils.SecurityUtils;
import com.tudouji.common.utils.StringUtils;
import com.tudouji.common.utils.sql.SqlUtil;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.framework.web.page.PageDomain;
import com.tudouji.framework.web.page.TableSupport;
import com.tudouji.project.flow.utils.FlowProcessUtil;
import com.tudouji.project.harvest.domain.Freightorder;
import com.tudouji.project.harvest.domain.Procurementcontract;
import com.tudouji.project.harvest.mapper.FreightorderMapper;
import com.tudouji.project.harvest.mapper.ProcurementcontractMapper;
import com.tudouji.project.organization.domain.Organization;
import com.tudouji.project.organization.domain.Supplier;
import com.tudouji.project.organization.mapper.OrganizationMapper;
import com.tudouji.project.organization.mapper.SupplierMapper;
import com.tudouji.project.pay.domain.Payinfo;
import com.tudouji.project.pay.domain.PayinfoRecord;
import com.tudouji.project.pay.domain.Payorderlist;
import com.tudouji.project.pay.mapper.PayinfoMapper;
import com.tudouji.project.pay.mapper.PayinfoRecordMapper;
import com.tudouji.project.pay.mapper.PayorderlistMapper;
import com.tudouji.project.pay.service.IPayinfoService;
import com.tudouji.project.permission.domain.Salespermission;
import com.tudouji.project.permission.service.ISalespermissionService;
import com.tudouji.project.purchasebill.domain.Purchasebill;
import com.tudouji.project.purchasebill.mapper.PurchasebillMapper;
import com.tudouji.project.store.domain.Storeroom;
import com.tudouji.project.store.mapper.StoreroomMapper;
import com.tudouji.project.system.domain.SysDept;
import com.tudouji.project.system.domain.SysUser;
import com.tudouji.project.system.mapper.SysDeptMapper;
import com.tudouji.project.system.service.impl.BusinesscodeServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 支付Service业务层处理
 *
 * @author tudouji
 * @date 2021-04-06
 */
@Slf4j
@Service
public class PayinfoServiceImpl implements IPayinfoService , IFlowBaseService {
    @Autowired
    private PayinfoMapper payinfoMapper;
    @Autowired
    private PayorderlistMapper payorderlistMapper;
    @Autowired
    private FreightorderMapper freightorderMapper;
    @Autowired
    private PurchasebillMapper purchasebillMapper;
    @Autowired
    private ISalespermissionService permissionService;
    @Autowired
    private FlowProcessUtil processUtils;
    @Autowired
    private FlowProcessProxy processProxy;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private StoreroomMapper storeroomMapper;
    @Autowired
    private ProcurementcontractMapper procurementcontractMapper;
    @Autowired
    private BusinesscodeServiceImpl codeService;
    @Autowired
    private PayinfoRecordMapper payinfoRecordMapper;
    @Autowired
    private SupplierMapper supplierMapper;

    /**
     * 查询支付
     *
     * @param guid 支付ID
     * @return 支付
     */
    @Override
    public Payinfo selectPayinfoById(String guid) {
        return payinfoMapper.selectPayinfoById(guid);
    }
    @Override
    public Payinfo selectPayinfoDetailById(Long guid) {
        Payinfo payinfo = payinfoMapper.selectPayinfoByAutoId(guid);
        if (StringUtils.equalsIgnoreCase("19", payinfo.getFlowid())){
            return payinfoMapper.selectPayinfoDetailOldById(guid);
        }else{
            return payinfoMapper.selectPayinfoDetailById(guid);
        }
    }
    @Override
    public Payinfo selectPayinfoByAutoId(Long id) {
        return payinfoMapper.selectPayinfoByAutoId(id);
    }

    /**
     * 查询支付列表
     *
     * @param payinfo 支付
     * @return 支付
     */
    @Override
    public List<Payinfo> selectPayinfoListOld(Payinfo payinfo) {
        return payinfoMapper.selectPayinfoListOld(payinfo);
    }
    @Override
    public List<Payinfo> selectPayinfoList(Payinfo payinfo) {
        return payinfoMapper.selectPayinfoList(payinfo);
    }
    @Override
    public List<Payinfo> selectPayinfoListFo(Payinfo payinfo) {
        return payinfoMapper.selectPayinfoListFo(payinfo);
    }
    @Override
    public List<Payinfo> selectPayinfoListFl(Payinfo payinfo) {
        return payinfoMapper.selectPayinfoListFl(payinfo);
    }

    /**
     * 新增支付
     *
     * @param payinfo 支付
     * @return 结果
     */
    @Override
    public int insertPayinfo(Payinfo payinfo) {
        return payinfoMapper.insertPayinfo(payinfo);
    }

    /**
     * 修改支付
     *
     * @param payinfo 支付
     * @return 结果
     */
    @Override
    public int updatePayinfo(Payinfo payinfo) {
        return payinfoMapper.updatePayinfo(payinfo);
    }

    /**
     * 批量删除支付
     *
     * @param guids 需要删除的支付ID
     * @return 结果
     */
    @Override
    public int deletePayinfoByIds(String[] guids) {
        return payinfoMapper.deletePayinfoByIds(guids);
    }

    /**
     * 删除支付信息
     *
     * @param guid 支付ID
     * @return 结果
     */
    @Override
    public int deletePayinfoById(String guid) {
        return payinfoMapper.deletePayinfoById(guid);
    }


    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageNum, pageSize, orderBy);
        }
    }

    @Override
    public List<Payinfo> listWx(Payinfo payinfo, String status, String functionType) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        if (payinfo == null) {
            payinfo = new Payinfo();
        }
        if (StringUtils.isNotBlank(status)) {
            // 待处理
            if (status.equals("00")) {
                startPage();
                payinfo.setCreateBy(sysUser.getUserId());
                return payinfoMapper.selectApplyPendingList(payinfo);
            } else {
                String[] sts = status.split(",");
                Integer[] stss = (Integer[]) ConvertUtils.convert(sts, Integer.class);
                payinfo.setStats(stss);
            }
        }

        List<Salespermission> permissions = permissionService.getPermByScAndFuncSYS(sysUser.getUserId(), functionType, "4");
        if (permissions.size() > 0) {
            startPage();
            return payinfoMapper.selectPayinfoList(payinfo);
        } else {
            payinfo.setCondition("none");
            payinfo.setCreateBy(sysUser.getUserId());
            payinfo.setOperatorid(sysUser.getTuserId());
            //部门权限
            permissions = permissionService.getPermByScAndFuncSYS(sysUser.getUserId(), functionType, "2");
            if (permissions.size() > 0) {
                String[] departids = new String[permissions.size()];
                for (int i = 0; i < permissions.size(); i++) {
                    departids[i] = permissions.get(i).getDepartid();
                }
                payinfo.setDepartids(departids);
            }
            //库房权限
            permissions = permissionService.getPermByScAndFuncSYS(sysUser.getUserId(), functionType, "7");
            if (permissions.size() > 0) {
                String[] strguids = new String[permissions.size()];
                for (int i = 0; i < permissions.size(); i++) {
                    strguids[i] = permissions.get(i).getSrguid();
                }
                payinfo.setStrguids(strguids);
            }
            startPage();
            return payinfoMapper.selectPayinfoList(payinfo);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult save(Payinfo payinfo, String fileIds, Long taskid, String opinion) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        payinfo.setOperatorid(sysUser.getGuid());
        payinfo.setCreateBy(sysUser.getUserId());
        String guid = IdUtils.fastSimpleUUID();
        payinfo.setGuid(guid);
//        payinfo.setFlowid("41");
        payinfo.setStatus(-1);
        payinfo.setCreatedate(DateUtils.getNowDate());

        if (1 == payinfo.getBusinessType()){
            AjaxResult error = setFreightorder(payinfo, sysUser, guid);
            if (error != null) {
                return error;
            }
        }else {
            AjaxResult error = setPurchasebill(payinfo, sysUser, guid);
            if (error != null) {
                return error;
            }
        }

        payinfo.setPlatformId(payinfo.getStorermId());
        if (2 == payinfo.getBusinessType()){
            Supplier supplier = new Supplier();
            supplier.setId(payinfo.getSupplierId());
            supplier.setBank(payinfo.getBank());
            supplier.setBankcode(payinfo.getBankcode());
            supplierMapper.updateSupplier(supplier);
        }
        FlowResult result = processProxy.start(processUtils.getStartNode(Long.valueOf(payinfo.getFlowid())), payinfo, fileIds
                , sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Payinfo pb = new Payinfo();
            pb.setStatus(result.getNextStat());
            pb.setGuid(guid);
            this.updatePayinfo(pb);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    private AjaxResult setFreightorder(Payinfo payinfo, SysUser sysUser, String guid) {
        String ids = payinfo.getFreightorderIds();
        if (ids == null) {
            return AjaxResult.error("未选中任何货运单!");
        }
        String[] idss = ids.split(",");
        Freightorder order = new Freightorder();
        order.setGuids(idss);
        List<Freightorder> orders = freightorderMapper.selectFreightorderList(order);
        BigDecimal settlementAmout = new BigDecimal(0);
        BigDecimal weightAmout = new BigDecimal(0);
        for (int i = 0; i < orders.size(); i++) {
            if (orders.get(i).getPaystatus() > 2) {
                return AjaxResult.error("已提交付款申请！");
            }
            BigDecimal settlement = orders.get(i).getSettlement();
            BigDecimal weight;
            if (StringUtils.equals(orders.get(i).getSetlwgtype(), "1")) {
                weight = orders.get(i).getWeight();
            } else {
                weight = orders.get(i).getHweight();
            }
            settlementAmout = settlementAmout.add(settlement);
            weightAmout = weightAmout.add(weight);
        }
        payinfo.setAmount(settlementAmout);
        payinfo.setRecamount(settlementAmout);
        payinfo.setCarnum(orders.size());
        payinfo.setWeight(weightAmout);
        Procurementcontract proConteact = procurementcontractMapper.selectProcurementcontractById(orders.get(0).getContractid());
        Supplier supplier = supplierMapper.selectSupplierById(orders.get(0).getSupplierId());
        payinfo.setOrgid(proConteact.getOrganizationid());
        payinfo.setOrgname(proConteact.getParta());
        payinfo.setDepartid(proConteact.getDepartid());
        payinfo.setDepartname(proConteact.getDepartname());
        payinfo.setSupplierId(supplier.getId());
        payinfo.setSupplierName(supplier.getName());
        payinfo.setCode(codeService.getCode("21"));
        if (settlementAmout.compareTo(payinfo.getApplyAmount()) == -1) {
            return AjaxResult.error("申请支付金额不能大于结算金额");
        }
        payinfo.setSrguid(orders.get(0).getStrguid());
        payinfo.setStorermId(orders.get(0).getStrid());


        SysDept sysDept = sysDeptMapper.selectDeptByGuid(payinfo.getDepartid());
        Organization organization = organizationMapper.selectOrganizationById(payinfo.getOrgid());
        Storeroom storeroom = storeroomMapper.selectStoreroomByGuid(payinfo.getSrguid());
        payinfo.setDeptId(sysDept.getDeptId());
        payinfo.setOrgId(organization.getId());
        payinfo.setStorermId(storeroom.getId());
        payinfoMapper.insertPayinfo(payinfo);
        //循环货运单，插入payorderlist
        if (orders.size() > 0) {
            for (int i = 0; i < orders.size(); i++) {
                Payorderlist paylist = new Payorderlist();
                Freightorder e = orders.get(i);
                paylist.setAmount(e.getSettlement());
                paylist.setOperatorid(sysUser.getGuid());
                paylist.setPayinfoguid(guid);
                paylist.setPayinfoId(payinfo.getId());
                paylist.setFoguid(e.getGuid());
                paylist.setFocode(e.getCode());
                paylist.setCreatedate(DateUtils.getNowDate());
                paylist.setBusinessType(payinfo.getBusinessType());
                paylist.setGuid(IdUtils.fastSimpleUUID());
                payorderlistMapper.insertPayorderlist(paylist);
                e.setPaystatus(3);
                freightorderMapper.updateFreightorder(e);
            }
        }
        return null;
    }

    private AjaxResult setPurchasebill(Payinfo payinfo, SysUser sysUser, String guid) {
        String ids = payinfo.getFreightorderIds();
        if (ids == null) {
            return AjaxResult.error("未选中任何采购单!");
        }
        String[] idss = ids.split(",");
        Purchasebill order = new Purchasebill();
        order.setGuids(idss);
        List<Purchasebill> orders = purchasebillMapper.selectPurchasebillListMain(order);
        BigDecimal settlementAmout = new BigDecimal(0);
        BigDecimal weightAmout = new BigDecimal(0);
        for (int i = 0; i < orders.size(); i++) {
            if (orders.get(i).getPaystatus() > 2) {
                return AjaxResult.error("已提交付款申请！");
            }
            BigDecimal settlement = orders.get(i).getTotalamount();
            BigDecimal weight = orders.get(i).getTotalnum();
            settlementAmout = settlementAmout.add(settlement);
            weightAmout = weightAmout.add(weight);
        }
        payinfo.setAmount(settlementAmout);
        payinfo.setRecamount(settlementAmout);
        payinfo.setCarnum(orders.size());
        payinfo.setWeight(weightAmout);
        Supplier supplier = supplierMapper.selectSupplierById(Long.valueOf(orders.get(0).getSupplierid()));
        payinfo.setOrgid(orders.get(0).getOrgid());
        payinfo.setOrgname(orders.get(0).getOrgname());
        payinfo.setDepartid(orders.get(0).getDepartid());
        payinfo.setDepartname(orders.get(0).getDepartment());
        payinfo.setSrguid(orders.get(0).getSrguid());
        payinfo.setStorermId(orders.get(0).getStrmId());
        payinfo.setSupplierId(supplier.getId());
        payinfo.setSupplierName(supplier.getName());
        payinfo.setCode(codeService.getCode("21"));
        if (settlementAmout.compareTo(payinfo.getApplyAmount()) == -1) {
            return AjaxResult.error("申请支付金额不能大于结算金额");
        }


        SysDept sysDept = sysDeptMapper.selectDeptByGuid(payinfo.getDepartid());
        Organization organization = organizationMapper.selectOrganizationById(payinfo.getOrgid());
        Storeroom storeroom = storeroomMapper.selectStoreroomByGuid(payinfo.getSrguid());
        payinfo.setDeptId(sysDept.getDeptId());
        payinfo.setOrgId(organization.getId());
        payinfo.setStorermId(storeroom.getId());
        payinfoMapper.insertPayinfo(payinfo);
        //循环货运单，插入payorderlist
        if (orders.size() > 0) {
            for (int i = 0; i < orders.size(); i++) {
                Payorderlist paylist = new Payorderlist();
                Purchasebill e = orders.get(i);
                paylist.setAmount(e.getTotalamount());
                paylist.setOperatorid(sysUser.getGuid());
                paylist.setPayinfoguid(guid);
                paylist.setPayinfoId(payinfo.getId());
                paylist.setFoguid(e.getGuid());
                paylist.setFocode(e.getCode());
                paylist.setCreatedate(DateUtils.getNowDate());
                paylist.setBusinessType(payinfo.getBusinessType());
                paylist.setGuid(IdUtils.fastSimpleUUID());
                payorderlistMapper.insertPayorderlist(paylist);
                e.setPaystatus(3);
                purchasebillMapper.updatePurchasebill(e);
            }
        }
        return null;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult approval(Long id, Long taskid, String opinion, String fileIds) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        return commonApproval(id, taskid, opinion, fileIds, sysUser);
    }

    private AjaxResult commonApproval(Long id, Long taskid, String opinion, String fileIds, SysUser sysUser) {
        Payinfo payinfo = payinfoMapper.selectPayinfoByAutoId(id);

        payinfo.setPlatformId(payinfo.getStorermId());
        FlowResult result = processProxy.approval(taskid, fileIds, opinion, payinfo
                , sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Payinfo pb = new Payinfo();
            pb.setStatus(result.getNextStat());
            pb.setId(id);
            this.updatePayinfo(pb);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult refuse(Long id, String fileIds, String opinion, Long taskid, Long refuseNodeid, Long backUserid) {
        Payinfo payinfo = payinfoMapper.selectPayinfoByAutoId(id);
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        payinfo.setPlatformId(payinfo.getStorermId());
        FlowResult result = processProxy.refuse(taskid, fileIds, opinion, payinfo
                , sysUser, refuseNodeid, backUserid);

        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Payinfo pb = new Payinfo();
            pb.setStatus(result.getNextStat());
            pb.setId(id);
            this.updatePayinfo(pb);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult del(Long id) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Payinfo apply = payinfoMapper.selectPayinfoByAutoId(id);

        Payinfo payinfo = new Payinfo();
        payinfo.setId(id);
        payinfo.setStatus(0);
        payinfoMapper.updatePayinfo(payinfo);

        List<Payorderlist> items = payorderlistMapper.selectPayorderlistByPayinfoguid(apply.getGuid());
        if (items.size() > 0) {
            for (int i = 0; i < items.size(); i++) {
                Payorderlist it = items.get(i);
                if (1 == apply.getBusinessType()){
                    Freightorder order = new Freightorder();
                    order.setGuid(it.getFoguid());
                    order.setPaystatus(2);
                    freightorderMapper.updateFreightorder(order);
                }else{
                    Purchasebill order = new Purchasebill();
                    order.setGuid(it.getFoguid());
                    order.setPaystatus(2);
                    purchasebillMapper.updatePurchasebill(order);
                }
            }
        }
        //更新待处理任务
        processUtils.updateTaskByOrderId(id, sysUser, Long.valueOf(apply.getFlowid()));
        return AjaxResult.success();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult finance(Long id, Long taskid, String opinion, String fileIds, Integer invoiceOn) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Payinfo payinfo = payinfoMapper.selectPayinfoByAutoId(id);

        payinfo.setPlatformId(payinfo.getStorermId());
        FlowResult result = processProxy.approval(taskid, fileIds, opinion, payinfo
                , sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Payinfo pb = new Payinfo();
            pb.setStatus(result.getNextStat());
            pb.setInvoiceon(invoiceOn);
            pb.setId(id);
            this.updatePayinfo(pb);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult pay(Long id, Long taskid, String opinion, String fileIds, BigDecimal applyAmount, Integer continuepayFlag) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Payinfo info = payinfoMapper.selectPayinfoByAutoId(id);

        /** 更新已付款，为付款金额，记录支付流水*/
        Payinfo payinfo = new Payinfo();
        BigDecimal preAmount = null;
        BigDecimal recAmount = null;
        preAmount = (info.getPreamount() == null ? BigDecimal.ZERO : info.getPreamount()).add(applyAmount);
        recAmount = info.getAmount().subtract(preAmount);
        if (recAmount.compareTo(BigDecimal.ZERO) == -1){
            return AjaxResult.error("支付金额不能大于未付金额!");
        }
        payinfo.setId(id);
        payinfo.setPreamount(preAmount);
        payinfo.setRecamount(recAmount);
        payinfo.setApplyAmount(applyAmount);
        payinfo.setContinuepayFlag(continuepayFlag);
        payinfoMapper.updatePayinfo(payinfo);
        payinfo = payinfoMapper.selectPayinfoByAutoId(id);
        FlowResult result = processProxy.approval(taskid, fileIds, opinion, payinfo
                , sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Payinfo pb = new Payinfo();
            pb.setStatus(result.getNextStat());
            pb.setId(id);
            this.updatePayinfo(pb);
            if (1 == payinfo.getBusinessType()){
                updateFreightorders(payinfo.getGuid());
            }else{
                updatePurchasebills(payinfo.getGuid());
            }
            insertRecord(applyAmount, sysUser, preAmount, recAmount, payinfo.getGuid());
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public AjaxResult finalPay(Long id, Long taskid, String opinion, String fileIds, BigDecimal applyAmount) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Payinfo info = payinfoMapper.selectPayinfoByAutoId(id);
        if (info.getRecamount().compareTo(applyAmount) == -1){
            return AjaxResult.error("支付金额不能大于未付金额!");
        }
        FlowResult result = processProxy.approval(taskid, fileIds, opinion, info
                , sysUser);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            Payinfo pb = new Payinfo();
            pb.setStatus(result.getNextStat());
            pb.setId(id);
            pb.setApplyAmount(applyAmount);
            this.updatePayinfo(pb);
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error(result.getMsg());
        }
    }

    @Override
    public AjaxResult getUnPayFreightorder() {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Freightorder freightorder = new Freightorder();
        freightorder.setPaystatus(2);
        freightorder.setNostats(new Integer[]{-1, 0});
        freightorder.setCreateBy(sysUser.getUserId());
        //部门权限
        List<Salespermission> permissions = permissionService.getPermByScAndFuncSYS(sysUser.getUserId(), null, "2");
        if (permissions.size() > 0) {
            String[] departids = new String[permissions.size()];
            for (int i = 0; i < permissions.size(); i++) {
                departids[i] = permissions.get(i).getDepartid();
            }
            freightorder.setDepartids(departids);
        }
        return AjaxResult.success(freightorderMapper.selectFreightorderList(freightorder));
    }

    @Override
    public AjaxResult statisticsOrderByPlan(Long orgId, Long supplierId, String keywords) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        Freightorder freightorder = new Freightorder();
        freightorder.setOrgId(orgId);
        freightorder.setSupplierId(supplierId);
        freightorder.setOperatorid(sysUser.getTuserId());
        freightorder.setKeywords(keywords);
        List<Freightorder> freightorders = freightorderMapper.statisticsOrderFive(freightorder);
        return AjaxResult.success(freightorders);
    }

    @Override
    public AjaxResult getUnPayFreightorders(Long orgId, Long supplierId) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Freightorder freightorder = new Freightorder();
        freightorder.setOrgId(orgId);
        freightorder.setSupplierId(supplierId);
        freightorder.setOperatorid(sysUser.getTuserId());
        List<Freightorder> freightorders = freightorderMapper.statisticsOrderByPlan(freightorder);
        return AjaxResult.success(freightorders);
    }

    @Override
    public AjaxResult getUnPayPurchasebills(Long orgId, Long supplierId) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();

        Purchasebill purchasebill = new Purchasebill();
        purchasebill.setOrgId(orgId);
        purchasebill.setSupplierId(supplierId);
        purchasebill.setOperatorid(sysUser.getTuserId());
        List<Purchasebill> purchasebills = purchasebillMapper.getUnPayPurchasebills(purchasebill);
        return AjaxResult.success(purchasebills);
    }

    @Override
    public AjaxResult getUnPayPurchasebillGroup(Long orgId, Long supplierId, String keywords) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Purchasebill purchasebill = new Purchasebill();
        purchasebill.setOrgId(orgId);
        purchasebill.setSupplierId(supplierId);
        purchasebill.setOperatorid(sysUser.getTuserId());
        purchasebill.setKeywords(keywords);
        List<Purchasebill> purchasebills = purchasebillMapper.getUnPayPurchasebillGroup(purchasebill);
        return AjaxResult.success(purchasebills);
    }

    private void insertRecord(BigDecimal applyAmount, SysUser sysUser, BigDecimal preAmount, BigDecimal recAmount, String guid) {
        PayinfoRecord record = new PayinfoRecord();
        record.setPayguid(guid);
        record.setPreamount(preAmount);
        record.setRecamount(recAmount);
        record.setAmount(applyAmount);
        record.setCreatedate(new Date());
        record.setCreateBy(sysUser.getUserId() + "");
        record.setCreatebyName(sysUser.getNickName());
        record.setGuid(IdUtils.fastSimpleUUID());
        payinfoRecordMapper.insertPayinfoRecord(record);
    }

    private void updateFreightorders(String guid) {
        List<Payorderlist> items = payorderlistMapper.selectPayorderlistByPayinfoguid(guid);
        if (items.size() > 0) {
            for (int i = 0; i < items.size(); i++) {
                Payorderlist it = items.get(i);
                Freightorder fo = new Freightorder();
                fo.setGuid(it.getFoguid());
                Freightorder freightorder = freightorderMapper.selectFreightorderDetailById(it.getFoguid());
                if (freightorder.getPaystatus() != 4){
                    fo.setPaystatus(4);
                    freightorderMapper.updateFreightorder(fo);
                }
            }
        }
    }

    private void updatePurchasebills(String guid) {
        List<Payorderlist> items = payorderlistMapper.selectPayorderlistByPayinfoguid(guid);
        if (items.size() > 0) {
            for (int i = 0; i < items.size(); i++) {
                Payorderlist it = items.get(i);
                Purchasebill fo = new Purchasebill();
                Purchasebill purchasebill = purchasebillMapper.selectPurchasebillByGuid(it.getFoguid());
                fo.setId(purchasebill.getId());
                if (purchasebill.getPaystatus() != 4){
                    fo.setPaystatus(4);
                    purchasebillMapper.updatePurchasebill(fo);
                }
            }
        }
    }

    @Override
    public BasePojo getBaseById(Long id) {
        return selectPayinfoByAutoId(id);
    }

    @Override
    public BasePojo getBaseByCode(String code) {
        return payinfoMapper.selectPayinfoByCode(code);
    }
}
